package com.meiyou.service.impl;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.xml.bind.DatatypeConverter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.rtc.model.v20180111.CreateChannelRequest;
import com.aliyuncs.rtc.model.v20180111.CreateChannelResponse;
import com.meiyou.mapper.MeiyouSettingMapper;
import com.meiyou.mapper.MeiyouShipinlsMapper;
import com.meiyou.mapper.MeiyouUserMapper;
import com.meiyou.pojo.MeiyouSettingExample;
import com.meiyou.pojo.MeiyouShipinls;
import com.meiyou.service.AliyunVideoService;
import com.meiyou.utils.Context;
import com.meiyou.utils.Msg;

@Service
public class AliyunVideoServiceImpl implements AliyunVideoService{
    
	
	private String regionID = "cn-hangzhou";
	private String endpoint = "rtc.aliyuncs.com";
	Msg msg;
	@Autowired
	MeiyouUserMapper userMapper;
	@Autowired
	MeiyouSettingMapper settingMapping;
	@Autowired
	MeiyouShipinlsMapper shipinlsMapper;
	
	/**
	 * 创建频道生成鉴权私钥
	 */
	public Msg createChannel(String appID, String channelID) {
		// TODO Auto-generated method stub
		
		try {
	        DefaultProfile profile = DefaultProfile.getProfile(regionID, Context.VIDEOACCESSKEYID, Context.VIDEOACCESSKEYSECRET);
	        DefaultAcsClient client = new DefaultAcsClient(profile);
	        CreateChannelRequest request = new CreateChannelRequest();
	        request.setAppId(appID);
	        request.setChannelId(channelID);
	        DefaultProfile.addEndpoint(regionID, regionID, request.getProduct(), endpoint);
	        // Use HTTP, x3 times faster than HTTPS.
	        request.setProtocol(ProtocolType.HTTP);
	        client.setAutoRetry(true);
	        client.setMaxRetryNumber(3);
	        request.setConnectTimeout(2000);
	        request.setReadTimeout(3000);
	        CreateChannelResponse response = client.getAcsResponse(request);
	        Map<String,Object> map = new HashMap<String,Object>();
	        map.put("appId", appID);
	        map.put("channelID", channelID);
	        map.put("nonce", response.getNonce());
	        map.put("timestamp", response.getTimestamp());
	        map.put("channelKey", response.getChannelKey());
	        map.put("recovered", false);
	        map.put("requestID", response.getRequestId());
	        msg = Msg.success();
	        msg.setExtend(map);
	        return msg;
	    } catch (ClientException ex) {
	    	boolean fatal = false;
	 	    if (ex != null) {
	 	        String code = ex.getErrCode();
	 	        if (code.equalsIgnoreCase("IllegalOperationApp")) {
	 	            fatal = true;
	 	        } else if (code.startsWith("InvalidAccessKeyId")) {
	 	            fatal = true;
	 	        } else if (code.equalsIgnoreCase("SignatureDoesNotMatch")) {
	 	            fatal = true;
	 	        }
	 	    }
	 	    if (fatal) {
	 	        try {
					throw ex;
				} catch (ClientException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	 	    }
	 	    String recover = String.format("RCV-%s", UUID.randomUUID().toString());
	 	   Map<String,Object> map = new HashMap<String,Object>();
	 	    map.put("appId", appID);
	        map.put("channelID", channelID);
	        map.put("nonce",recover);
	        map.put("timestamp", 0);
	        map.put("channelKey", recover);
	        map.put("recovered", true);
	        map.put("requestID", ex.getRequestId());
	 	    System.out.printf("Recover from error:\n");
	 	    ex.printStackTrace();
	 	    msg = Msg.fail();
	 	    msg.setExtend(map);
	 	    return msg;
	  }
		
	}
	
	
	/**
	 * 为客户端创建Token
	 */
	public String createToken( String appId, String userId, String channelId, String channelKey, String nonce,long timestamp) {
	    try {
			MessageDigest digest = MessageDigest.getInstance("SHA-256");
			digest.update(channelId.getBytes());
			digest.update(channelKey.getBytes());
			digest.update(appId.getBytes());
			digest.update(userId.getBytes());
			digest.update(nonce.getBytes());
			digest.update(Long.toString(timestamp).getBytes());
			String token = DatatypeConverter.printHexBinary(digest.digest()).toLowerCase();
			return token;
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}


	public Msg videoChat(String fromUccount, String toUccount) {
		Msg msg;
		// TODO Auto-generated method stub
		double hasmeijin = userMapper.selectByuccount(fromUccount).getUmeijin();
		double videoMeijin;
		
		//查询通话一次扣除美金
		MeiyouSettingExample example = new MeiyouSettingExample();
		MeiyouSettingExample.Criteria criteria = example.createCriteria();
		criteria.andJNameEqualTo("video");
		videoMeijin = Double.parseDouble(settingMapping.selectByExample(example).get(0).getjValue());
		
		//查询通话费率
		double fl;
		MeiyouSettingExample example1 = new MeiyouSettingExample();
		MeiyouSettingExample.Criteria criteria1 = example1.createCriteria();
		criteria1.andJNameEqualTo("video_fl");
		fl = Double.parseDouble(settingMapping.selectByExample(example).get(0).getjValue());
		if(hasmeijin>=videoMeijin) {
			double meijin = videoMeijin*((double)1-fl);
			if(userMapper.updAddMeijin(meijin, toUccount)>=1) {
				if(userMapper.updDelMeijin(videoMeijin, fromUccount)>=1) {
					MeiyouShipinls ls = new MeiyouShipinls();
					ls.setsMeijin((int)videoMeijin);
					ls.setsTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					ls.setsUCount(fromUccount);
					if(shipinlsMapper.insertSelective(ls)>=1) {
						msg = Msg.success();
						return msg;
					}
				}
			}
			msg = Msg.fail();
			return msg;
		}else {
			msg = Msg.fail();
			msg.setMsg("账号余额不足");
			return msg;
		}
	}
}
